package org.grenobus.html;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Map;
import java.util.TreeMap;

import android.util.Log;

public class SemitagHtmlPage {

	private SimpleHTML          fHtml;
	private Form                fForm;
	
	private String              fBaseUrl;
	private Map<String, String> fProperties;
	
	
	public SemitagHtmlPage(String url) {
		
		fProperties = new TreeMap<String, String>();

        final Calendar c = Calendar.getInstance();
        fProperties.put("selection_jour", Integer.toString(c.get(Calendar.DAY_OF_MONTH)));
		fProperties.put("selection_mois", Integer.toString(c.get(Calendar.MONTH)+1));
		fProperties.put("selection_annee", Integer.toString(c.get(Calendar.YEAR)));
		
		fBaseUrl = url.substring(0, url.lastIndexOf('/')+1); 
			
        try {
            /* Define the URL we want to load data from. */
        	URL myURL = new URL(url);
        	
            /* Open a connection to that URL. */
            URLConnection ucon = myURL.openConnection();

            /* Define InputStreams to read
             * from the URLConnection. */
            InputStream is = ucon.getInputStream();
            InputStream bis ;
            
            bis = new BufferedInputStream(is); 
            fHtml = new SimpleHTML("doc", null);
            fHtml.parse(bis, this);
            fHtml.cleanup();
            
        } catch (IOException e) {
			// TODO Auto-generated catch block
			Log.w("TestDroid", e.getMessage());
		}
	}
	
	public void setForm(Form f) {
		fForm = f;
	}
	
	public void setBaseUrl(String url) {
		fBaseUrl = url;
	}
	
	public Form getForm() {
		return fForm;
	}
	
	public void setProperty(String key, String val) {
		fProperties.put(key, val);
	}
	
	public SemitagHtmlPage postForm(String selectName, int selectPos) {
		String url = fForm.buildActionURL(fBaseUrl, fProperties, selectName, selectPos);
		return new SemitagHtmlPage(url);
	}

	public SimpleHTML getHtml() {
		return fHtml;
	}
	
}
